import axios from "axios"
import API from './index'
import { Message } from "element-ui"

const service = axios.create({
    baseURL: API.baseURL
})

//添加请求拦截器
service.interceptors.request.use(config => {
    //在发送请求之前做些什么
    if(!config.headers.token){
        let token = localStorage.getItem('token')
        if(token) config.headers.token = token
    }
    return config
},error => {
    //对请求错误做些什么
    return Promise.reject(error)
})

//添加响应拦截器
service.interceptors.response.use(function (response) {
    //对响应数据做点什么
    if(response.data.errorMsg){
        Message.error({
            message: response.data.errorMsg,
            type: 'error',
            duration: 1500
        })
    }
    return response.data
}, function (error) {
    let response = error.response
    switch(response.status){
        case 400:
            location.href ='#/login'
            break
        default:
            response = response.data
            Message.error({
                message: response.errorMsg || '未知错误',
                type: 'error',
                duration: 1500
            })
            break
    }
    //对响应错误做点什么
    return Promise.reject(response)
})

export default service